package com.hx.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * reentrantLock 带有condition的源码debug
 * @author minghuaChan
 * @since 2023/9/17 18:07
 */
public class ReentrantLockWithCondition {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock(true);
        Condition condition = lock.newCondition();


        Thread thread0 = new Thread(() -> {
            try {
                doSth1(lock, condition);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        thread0.start();

        Thread thread1 = new Thread(() -> {
            doSth2(lock, condition);
        });

        thread1.start();

//        Thread thread2 = new Thread(() -> {
//            try {
//                doSth1(lock, condition);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        });
//
//        thread2.start();

    }


    public static void doSth1(ReentrantLock lock, Condition condition) throws InterruptedException {
        // 锁住
        lock.lock();

        System.out.println(Thread.currentThread().getName() + "获取锁");


        // 校验是否可以处理
        System.out.println(Thread.currentThread().getName() + " 不满足条件,需要二次校验");
        condition.await();

        System.out.println(Thread.currentThread().getName() + "任务处理完毕");
        // 释放锁
        lock.unlock();

        System.out.println(Thread.currentThread().getName() + "释放锁");
    }


    public static void doSth2(ReentrantLock lock, Condition condition) {
        // 锁住
        lock.lock();

        System.out.println(Thread.currentThread().getName() + "获取锁");


        // 校验是否可以处理
        System.out.println("二次校验通过,可以处理");
        condition.signal();


        // 释放锁
        lock.unlock();

        System.out.println(Thread.currentThread().getName() + "释放锁");
    }

}
